package com.controller;

import java.util.HashMap;
import java.util.Map;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.model.User;

@Controller
@RequestMapping("/user")
public class UserController {
    private Map<String, User> users=new HashMap<String, User>();
    public UserController(){
    	users.put("xm", new User("xm","123","xiaoming","123@qq.com"));
    	users.put("xh", new User("xh","123","xiaohing","345@qq.com"));
    	users.put("xk", new User("xk","123","xiaoking","567@qq.com"));
    	users.put("xl", new User("xl","123","xiaoling","789@qq.com"));
    } 
    @RequestMapping(value="/users",method=RequestMethod.GET)
    public String list(Model m){
 	   m.addAttribute("users", users);
 	   return "user/list";
    }
    @RequestMapping(value="/add",method=RequestMethod.GET)
    public String add1(@ModelAttribute("user") User user){
//    	m.addAttribute(new User());
    	return "user/add";
    }
    @RequestMapping(value="/add",method=RequestMethod.POST)
    public String add(@Validated User user,BindingResult br){
    	if(br.hasErrors()){
            return "user/add";
    	}
    	users.put(user.getUsername(), user);
    	return "redirect:/user/users";
    }
    @RequestMapping(value="/(username)",method=RequestMethod.GET)
    public String show(@PathVariable String username,Model m){
    	m.addAttribute(users.get(username));
    	return "user/show";
    }
    @RequestMapping(value="/(username)/update",method=RequestMethod.GET)
    public String update(@PathVariable String username,Model m){
        m.addAttribute(users.get(username));
        return "user/update";
    }
    @RequestMapping(value="/(username)/update",method=RequestMethod.POST)
    public String update(@PathVariable String username,@Validated User user,BindingResult br){
    	if(br.hasErrors()){
    		return "user/update";
    	}
    	users.put(username, user);
    	return "redirect:user/users";
    }
}
